package com.jetwinner.webfast.module.bigapp.dao.impl;

import com.jetwinner.util.EasyStringUtil;
import com.jetwinner.util.FastHashMap;
import com.jetwinner.webfast.dao.support.DynamicQueryBuilder;
import com.jetwinner.webfast.dao.support.FastJdbcDaoSupport;
import com.jetwinner.webfast.kernel.dao.support.OrderBy;
import com.jetwinner.webfast.kernel.exception.RuntimeGoingException;
import com.jetwinner.webfast.module.bigapp.dao.AppGroupThreadDao;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * @author xulixin
 */
@Repository
public class AppGroupThreadDaoImpl extends FastJdbcDaoSupport implements AppGroupThreadDao {

    private final String TABLE_NAME = "big_app_group_thread";

    @Override
    public int searchThreadsCount(Map<String, Object> conditions) {
        DynamicQueryBuilder builder = this.createThreadSearchBuilder(conditions)
                .select("count(id)");
        return getNamedParameterJdbcTemplate().queryForList(builder.getSQL(),
                conditions, Integer.class).stream().findFirst().orElse(0);
    }

    @Override
    public List<Map<String, Object>> searchThreads(Map<String, Object> conditions, OrderBy orderBy,
                                                   Integer start, Integer limit) {

        DynamicQueryBuilder builder = this.createThreadSearchBuilder(conditions)
                .select("*")
                .orderBy(orderBy)
                .setFirstResult(start)
                .setMaxResults(limit);

        return getNamedParameterJdbcTemplate().queryForList(builder.getSQL(), conditions);
    }

    @Override
    public Map<String, Object> addThread(Map<String, Object> thread) {
        int threadId = insertMapReturnKey(TABLE_NAME, thread).intValue();
        if (threadId <= 0) {
            throw new RuntimeGoingException("Insert Thread error.");
        }

        return getThread(threadId);
    }

    public Map<String, Object> getThread(Integer id) {
        String sql = String.format("SELECT * from %s where id=? LIMIT 1", TABLE_NAME);
        return getJdbcTemplate().queryForList(sql, id).stream().findFirst().orElse(FastHashMap.build().toMap());
    }

    private DynamicQueryBuilder createThreadSearchBuilder(Map<String, Object> conditions) {
        if (EasyStringUtil.isNotBlank(conditions.get("title"))) {
            conditions.put("title", "%" + conditions.get("title") + "%");
        }

        return new DynamicQueryBuilder(conditions)
                .from(TABLE_NAME)
                .andWhere("groupId = :groupId")
                .andWhere("createdTime > :createdTime")
                .andWhere("isElite = :isElite")
                .andWhere("isStick = :isStick")
                .andWhere("type = :type")
                .andWhere("userId = :userId")
                .andWhere("status = :status")
                .andWhere("title like :title");
    }
}
